package cn.yuanqiao.web.controller.archive.Identify;

import cn.yuanqiao.archive.Identify.domain.Destroy;
import cn.yuanqiao.archive.Identify.domain.DestroyCar;
import cn.yuanqiao.archive.Identify.domain.vo.DestroyCarVo;
import cn.yuanqiao.archive.Identify.service.DestroyService;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 销毁库
 */
@RestController
@RequestMapping("/archive/destroyKu")
public class DestroyController extends BaseController {
    @Autowired
    private DestroyService destroyService;

    @Log(title = "查询销毁库", businessType = BusinessType.SELECT)
    @PostMapping("/destroyKuList")
    public TableDataInfo destroyKuList(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = destroyService.getlist(json);
        return getDataTable(list);
    }

    @Log(title = "删除销毁库", businessType = BusinessType.DELETE)
    @PostMapping("/destroyDel")
    public AjaxResult destroyDel(@RequestBody JSONObject object){
        if(object.containsKey("ids") && StringUtils.isNotEmpty(object.getString("ids"))){
            destroyService.destroyDel(object.getString("ids"),object.getLong("categoryId"));
        }
        return AjaxResult.success();
    }

    @Log(title = "查询销毁车", businessType = BusinessType.SELECT)
    @GetMapping("/carlist")
    public TableDataInfo carlist() {
        List<DestroyCarVo> list = destroyService.findDestroyCarVo(null);
        return getDataTable(list);
    }

    @Log(title = "根据销毁单ID查询销毁车", businessType = BusinessType.SELECT)
    @PostMapping("/listById")
    public TableDataInfo listById(@RequestParam("destroyId") Long destroyId) {
        List<DestroyCarVo> list = destroyService.findDestroyCarVo(destroyId);
        return getDataTable(list);
    }

    @Log(title = "添加销毁车", businessType = BusinessType.INSERT)
    @PostMapping("/addCar")
    public AjaxResult addCar(@RequestBody JSONObject jsonObject) {
        JSONArray array = jsonObject.getJSONArray("addCarList");
        for(int i = 0;i<array.size();i++){
            DestroyCar destroyCar = array.getJSONObject(i).toJavaObject(DestroyCar.class);
            if(destroyCar.getCategoryId() == null || destroyCar.getDaId() == null || destroyCar.getDaType() == null){
                throw new ServiceException("参数错误!");
            }
            destroyService.insert(destroyCar);
        }
        return AjaxResult.success();
    }

    @Log(title = "删除销毁车", businessType = BusinessType.DELETE)
    @PostMapping("/delCar")
    public AjaxResult delCar(@RequestBody JSONObject object){
        if(object.containsKey("ids") && StringUtils.isNotEmpty(object.getString("ids"))){
            destroyService.deleteByIds(object.getString("ids"));
        }
        return AjaxResult.success();
    }

    @Log(title = "添加销毁单", businessType = BusinessType.INSERT)
    @PostMapping("/addDestroy")
    public AjaxResult addDestroy(@RequestBody Destroy destroy) {
        destroyService.addDestroy(destroy);
        return AjaxResult.success();
    }

    @Log(title = "销毁单列表", businessType = BusinessType.SELECT)
    @PostMapping("/destroyList")
    public TableDataInfo destroyList(@RequestParam("destroyName")String destroyName, @RequestParam("destroyDate")String destroyDate)
    {
        Destroy destroy = new Destroy();
        destroy.setDestroyName(destroyName);
        if(StringUtils.isNotEmpty(destroyDate) && !"null".equals(destroyDate)){
            destroy.setDestroyDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,destroyDate));
        }
        PageUtils.startPage();
        List<Destroy> list = destroyService.destroyList(destroy);
        return getDataTable(list);
    }

    @Log(title = "根据ID查询销毁单", businessType = BusinessType.SELECT)
    @PostMapping("/destroyById/{destroyId}")
    public AjaxResult destroyById(@PathVariable("destroyId") Long destroyId)
    {
        Destroy list = destroyService.destroyById(destroyId);
        return AjaxResult.success(list);
    }

    @Log(title = "办结销毁单", businessType = BusinessType.SELECT)
    @PostMapping("/endDestroy")
    public void endDestroy(@RequestParam("destroyId")Long destroyId)
    {
        destroyService.endDestroy(destroyId);
        //return AjaxResult.success();
    }

    @Log(title = "不同意销毁单", businessType = BusinessType.SELECT)
    @PostMapping("/backDestroy")
    public void backDestroy(@RequestParam("destroyId")Long destroyId)
    {
        destroyService.backDestroy(destroyId);
        //return AjaxResult.success();
    }

    @Log(title = "电子文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("destroyId")Long destroyId, MultipartFile file)
    {
        destroyService.upload(destroyId,file);
        return AjaxResult.success();
    }

    @Log(title = "清除电子文件", businessType = BusinessType.INSERT)
    @PostMapping("/clearFilePath")
    public AjaxResult clearFilePath(@RequestParam("destroyId")Long destroyId)
    {
        destroyService.clearFilePath(destroyId);
        return AjaxResult.success();
    }

    @Log(title = "下载监销单", businessType = BusinessType.DOWNLOAD)
    @GetMapping("/downloadDestroyFile/{destroyId}")
    public ResponseEntity<Resource> downloadDestroyFile(@PathVariable("destroyId") Long destroyId)
    {
        Destroy destroy = destroyService.destroyById(destroyId);
        // 加载文件作为资源
        File file = new File(destroy.getDestroyListPath());

        // 确保文件存在
        if (!file.exists() || !file.canRead()) {
            throw new ServiceException("文件不存在或不可读!");
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (IOException e) {
            // 记录异常信息
            logger.error(e.getMessage(),e);
            throw new ServiceException("读取文件时发生错误"+e.getMessage());
        }
    }

    @Log(title = "下载销毁清册", businessType = BusinessType.DOWNLOAD)
    @GetMapping("/downloadDestroyList/{destroyId}")
    public ResponseEntity<Resource> downloadDestroyList(@PathVariable("destroyId") Long destroyId)
    {
        String path = destroyService.download(destroyId);
        // 加载文件作为资源
        File file = new File(path);

        // 确保文件存在
        if (!file.exists() || !file.canRead()) {
            throw new ServiceException("文件不存在或不可读!");
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (IOException e) {
            // 记录异常信息
            logger.error(e.getMessage(),e);
            throw new ServiceException("读取文件时发生错误"+e.getMessage());
        }
    }

}
